import React, { useState, useEffect, useRef } from 'react';
import { LeftOutline, SendOutline, PictureOutline, SoundOutline } from 'antd-mobile-icons';
import { useNavigate } from 'react-router-dom';
import { authManager } from '../../../utils/auth';
import './CustomerService.css';

interface Message {
  id: string;
  content: string;
  sender: 'user' | 'service';
  timestamp: string;
  type: 'text' | 'image';
}

const CustomerService: React.FC = () => {
  const navigate = useNavigate();
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [isConnected, setIsConnected] = useState(false);
  const [userInfo, setUserInfo] = useState<any>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const wsRef = useRef<WebSocket | null>(null);

  useEffect(() => {
    // 获取用户信息
    const user = authManager.getUserInfo();
    if (!user) {
      alert('请先登录');
      navigate('/login');
      return;
    }
    setUserInfo(user);

    // 初始化消息
    const initialMessages: Message[] = [
      {
        id: '1',
        content: `${user.username || '用户'}, 早上好`,
        sender: 'service',
        timestamp: '10:00',
        type: 'text'
      },
      {
        id: '2',
        content: '你好',
        sender: 'user',
        timestamp: '10:00',
        type: 'text'
      },
      {
        id: '3',
        content: '请告诉我您遇到的具体问题,我会尽力提供帮助。',
        sender: 'service',
        timestamp: '10:00',
        type: 'text'
      },
      {
        id: '4',
        content: '我在使用APP时遇到了一些问题,希望能得到帮助。',
        sender: 'user',
        timestamp: '10:00',
        type: 'text'
      },
      {
        id: '5',
        content: '好的,谢谢...',
        sender: 'user',
        timestamp: '10:01',
        type: 'text'
      }
    ];
    setMessages(initialMessages);

    // 初始化WebSocket连接
    initWebSocket();

    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
    };
  }, [navigate]);

  const initWebSocket = () => {
    try {
      const ws = new WebSocket('ws://localhost:5000/ws/customer-service');
      wsRef.current = ws;

      ws.onopen = () => {
        console.log('WebSocket连接已建立');
        setIsConnected(true);
        
        // 发送用户认证信息
        const user = authManager.getUserInfo();
        if (user) {
          ws.send(JSON.stringify({
            type: 'auth',
            token: authManager.getAccessToken(),
            userInfo: user
          }));
        }
      };

      ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          handleWebSocketMessage(data);
        } catch (error) {
          console.error('解析WebSocket消息失败:', error);
        }
      };

      ws.onclose = () => {
        console.log('WebSocket连接已关闭');
        setIsConnected(false);
        // 尝试重连
        setTimeout(() => {
          if (!wsRef.current || wsRef.current.readyState === WebSocket.CLOSED) {
            initWebSocket();
          }
        }, 3000);
      };

      ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
        setIsConnected(false);
      };
    } catch (error) {
      console.error('WebSocket初始化失败:', error);
    }
  };

  const handleWebSocketMessage = (data: any) => {
    switch (data.type) {
      case 'message':
        const newMessage: Message = {
          id: Date.now().toString(),
          content: data.content,
          sender: data.sender,
          timestamp: new Date().toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
          }),
          type: data.messageType || 'text'
        };
        setMessages(prev => [...prev, newMessage]);
        break;
      case 'auth_success':
        console.log('客服认证成功');
        break;
      case 'error':
        console.error('客服服务错误:', data.message);
        break;
    }
  };

  const sendMessage = () => {
    if (!inputValue.trim() || !isConnected) return;

    const newMessage: Message = {
      id: Date.now().toString(),
      content: inputValue.trim(),
      sender: 'user',
      timestamp: new Date().toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      }),
      type: 'text'
    };

    setMessages(prev => [...prev, newMessage]);
    
    // 发送到WebSocket
    if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
      wsRef.current.send(JSON.stringify({
        type: 'message',
        content: inputValue.trim(),
        sender: 'user',
        messageType: 'text'
      }));
    }

    setInputValue('');
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const formatDate = () => {
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    
    const todayStr = today.toLocaleDateString('zh-CN');
    const yesterdayStr = yesterday.toLocaleDateString('zh-CN');
    
    return todayStr === new Date().toLocaleDateString('zh-CN') ? '今天' : 
           yesterdayStr === new Date().toLocaleDateString('zh-CN') ? '昨天' : 
           new Date().toLocaleDateString('zh-CN');
  };

  return (
    <div className="customer-service-page">
      {/* 头部导航 */}
      <div className="cs-header">
        <div className="back-btn" onClick={() => navigate('/index/profile')}>
          <LeftOutline />
        </div>
        <div className="header-content">
          <div className="header-icon">⚡</div>
          <div className="page-title">在线客服</div>
        </div>
        <div className="connection-status">
          <div className={`status-dot ${isConnected ? 'connected' : 'disconnected'}`}></div>
        </div>
      </div>

      {/* 聊天区域 */}
      <div className="chat-container">
        {/* 日期分隔符 */}
        <div className="date-separator">
          <span className="date-text">{formatDate()}</span>
        </div>

        {/* 消息列表 */}
        <div className="messages-container">
          {messages.map((message) => (
            <div key={message.id} className={`message ${message.sender}`}>
              <div className="message-bubble">
                <div className="message-content">
                  {message.type === 'text' ? (
                    <span className="message-text">{message.content}</span>
                  ) : (
                    <img src={message.content} alt="图片" className="message-image" />
                  )}
                </div>
                <div className="message-time">{message.timestamp}</div>
              </div>
            </div>
          ))}
          <div ref={messagesEndRef} />
        </div>
      </div>

      {/* 输入区域 */}
      <div className="input-container">
        <div className="input-bar">
          <input
            type="text"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="请输入"
            className="message-input"
            disabled={!isConnected}
          />
          <div className="input-actions">
            <PictureOutline className="action-icon" />
            <SoundOutline className="action-icon" />
          </div>
        </div>
        <button 
          className={`send-btn ${inputValue.trim() && isConnected ? 'active' : ''}`}
          onClick={sendMessage}
          disabled={!inputValue.trim() || !isConnected}
        >
          <SendOutline />
        </button>
      </div>
    </div>
  );
};

export default CustomerService;
